import { execSync, spawn, spawnSync } from "child_process";
import { BasePlatform } from "./BasePlatform";
import path from 'path';
import PackUtil from "../utils/PackUtil";
import { ChannelInfo } from "./PlatformConfig";
import { existsSync, readFileSync } from "fs";
import wechatci = require('miniprogram-ci');
export class WechatGame extends BasePlatform {
    public async afterBuildFinish() {
        let configPath = path.join(this.projectDir, "settings", "wechatgame.json");
        if (existsSync(configPath)) {
            let channelInfo: ChannelInfo = this.configData.platforms[this.curPackChannel];
            let remoteDir = PackUtil.compareVersion(this.configData.engineVer, "2.4.0") >= 0 ? "remote" : "res";
            let remotepath = path.join(this.outputPath, channelInfo.platform, remoteDir);
            // let remotepath = path.join(this.outputPath, channelInfo.platform, "remote");
            if (existsSync(remotepath) && channelInfo.remoteDir != "") {
                console.log('upload cdn res start');
                let cdnrespath = channelInfo.remoteDir;
                PackUtil.pullCDNRes(cdnrespath);
                PackUtil.moveFiles(remotepath, cdnrespath);
                PackUtil.uploadCDNRes(cdnrespath);
                console.log('upload cdn res finish');
            }
            let config = JSON.parse(readFileSync(configPath, { encoding: 'utf-8' }));
            const project = new wechatci.Project({
                appid: config.appid,
                type: 'miniGame',
                projectPath: path.join(this.outputPath, "wechatgame"),
                privateKeyPath: channelInfo.privatePath,
                ignores: ['node_modules/**/*'],
            })
            const uploadResut = await wechatci.upload({
                project,
                version: this.version,
                desc: `autopack-${this.version}-${new Date().toLocaleString()}`,
                setting: {
                    es6: true,
                },
                onProgressUpdate: console.log,
            });
            this.saveBackUpConfig();
        } else {
            console.error("please pack first in editor");
        }
        //上传
        await super.afterBuildFinish();
    }
}